package com.gupao.ssoserver.controller;

import com.gupao.ssoserver.util.JwtUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class SSOController {

    List<String> list = new ArrayList<String>();

    @RequestMapping(value = "/preLogin",method = RequestMethod.GET)
    public String preLogin(String url, HttpServletRequest request, Model model) {
        System.out.println(url);
        HttpSession session = request.getSession(false);
        //全局session是在这里验证的。。。
        //发现认证中心没有全局的session会话，， 那要怎么做呢，，创全局session并且生成token，  这些事在login controller里去做；
        if (session == null ) {
            model.addAttribute("url",url);
            return "login";
        }

        /*order进来发现已经有全局session了，这时候就不用跳到login界面了，直接去验证token即可*/

        //2   群众的眼睛是雪亮的
        else {
            //全局session已经有了，然后在session中取到token
            //然后要去授权给这个  子系统、 既然是授权，这时候又要去跳转了。
            String token= (String) session.getAttribute("token");
            return "redirect:http://"+url+"?token=" + token;
        }
    }







    @RequestMapping("/login")
    public String login(String username, String password, String url,  HttpServletRequest request) {
        if ("Jack".equals(username) && "123456".equals(password)) {
            String token= null;
            try {
                token = JwtUtil.createJwt();   //token  123456   uuid
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            System.out.println(token);

//            创全局session并且生成token，

            request.getSession().setAttribute("token", token);
            list.add(token);
            //http://www.user.com:8081/user/wel?token=sdfafddfdfa
            return "redirect:http://"+url+"?token=" + token;
        } else {
            return "login";
        }
    }

    @RequestMapping("/checkToken")
    @ResponseBody
    public String checkToken(String token) {
        System.out.println(JwtUtil.verifyJwt(token));
        //不是伪造的
        if (list.contains(token)&&JwtUtil.verifyJwt(token)) {
            return "correct";
        }
        return "incorrect";
    }
}
















